package org.xxpay.pay.channel.renren;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.springframework.stereotype.Component;
import org.xxpay.common.http.HttpRequestTemplate;
import org.xxpay.common.util.HtmlUtils;
import org.xxpay.common.util.sign.SignUtils;
import org.xxpay.common.util.str.StringUtils;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;

import java.util.Map;

@Component
public class RenrenPaymentService extends BasePayment {
    private final static String logPrefix = "【人人支付】";
    @Override
    public String getChannelName() {
        return RenrenConfig.CHANNEL_NAME;
    }

    /**
     * 支付下单
     * @param payOrder
     * @return
     */
    @Override
    public JSONObject pay(PayOrder payOrder) {
        return  doOrderReq(payOrder);
    }

    /**
     * 查询订单
     * @param payOrder
     * @return
     */
    @Override
    public JSONObject query(PayOrder payOrder) {
        RenrenConfig config = new RenrenConfig(getPayParam(payOrder));
        String payOrderId = payOrder.getPayOrderId();
        _log.info("{}开始查询通道订单,payOrderId={}", logPrefix, payOrderId);
        Map<String, Object> params = Maps.newHashMap();
        params.put("shid", config.getAppId());
        params.put("ddh",payOrder.getPayOrderId());
        params.put("sign", getSign(params, config.getPrivateKey()));
        _log.info("{}订单查询请求数据:{}", getChannelName(), JSON.toJSONString(params));
        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.postForObject(config.getRequestUrl()+RenrenConfig.REQ_PAY_QUERY_URL_FIXX, params, JSONObject.class);
        _log.info("{}响应数据:{}", getChannelName(), JSON.toJSONString(origin));
        // 响应对象
        JSONObject retObj = new JSONObject();
        if(true) {
            String payStatus = origin.getString("code");
            if(StringUtils.equals(payStatus,"0")){
                //支付成功
                retObj.put("status",2);
            }else{
                //支付中
                retObj.put("status",1);
            }
            retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_SUCCESS);
            retObj.put("channelOrderNo", origin.getString("ptddh"));
            retObj.put("channelObj", origin);
            return retObj;
        }
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, origin.getString("msg"));
        return retObj;
    }

    //下单具体实现
    private JSONObject doOrderReq(PayOrder payOrder){
        RenrenConfig config = new RenrenConfig(getPayParam(payOrder));
        Map<String,Object> params = Maps.newHashMap();
        //设置参数
        setParams(payOrder,config,params);
        _log.info("{}请求数据:{}", getChannelName(), JSON.toJSONString(params));
        //将订单改为支付中
        rpcCommonService.rpcPayOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
        JSONObject retObj = new JSONObject();
        String payForm = HtmlUtils.form(config.getRequestUrl()+RenrenConfig.REQ_PAY_URL_FIXX, HtmlUtils.POST, params);

        return buildPayResultOfForm(retObj, payOrder, payForm);
    }

    //设置下单请求参数
    private void setParams(PayOrder payOrder, RenrenConfig config, Map<String,Object> params){
        params.put("bb","1.0");
        params.put("shid", config.getAppId());
        params.put("ddh", payOrder.getPayOrderId());
        params.put("je", AmountUtil.convertCent2Dollar(String.valueOf(payOrder.getAmount())));
        params.put("zftd", config.getPayMode());
        params.put("ybtz", payConfig.getNotifyUrl(getChannelName()));
        params.put("tbtz", payOrder.getReturnUrl());
        params.put("ddmc", payOrder.getPayOrderId());
        params.put("ddbz", payOrder.getPayOrderId());
        params.put("sign", getSign(params, config.getPrivateKey()));
    }

    //获取sign
    private String getSign(Map<String,Object> params, String key){
        String signTxt = "shid="+params.get("shid").toString()+"&bb="+params.get("bb").toString()+"&zftd="+params.get("zftd").toString()
                +"&ddh="+params.get("ddh").toString()+"&je="+params.get("je").toString()+"&ddmc="+params.get("ddmc").toString()
                +"&ddbz="+params.get("ddbz").toString()+"&ybtz="+params.get("ybtz").toString()+"&tbtz="+params.get("tbtz").toString();
        _log.info("{}待签名字符串：{}", logPrefix, signTxt+"&key="+key);
        String sign = SignUtils.MD5.createSign(signTxt, "&"+key, SignUtils.CHARSET_UTF8);
        return sign;
    }
}
